from fastapi import FastAPI, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
import os
from contextlib import asynccontextmanager
from app.api.endpoints import doi, websocket,database

# 在文件顶部导入
from app.api.websockets.subscriber import websocket_subscriber
from app.core.config import settings
from app.core.arq_app import create_arq_pool
from arq import ArqRedis

@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动事件 - 在应用启动时执行
    websocket_subscriber.start()
    # 创建ARQ Redis连接池
    app.state.arq_redis = await create_arq_pool()
    yield
    # 关闭事件 - 在应用关闭时执行
    websocket_subscriber.stop()
    # 关闭ARQ Redis连接池
    await app.state.arq_redis.close()
 
app = FastAPI(title="sci-hub Downloader API", lifespan=lifespan)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该设置具体的源
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 在应用启动时添加以下代码
import os
from app.core.config import settings

# 确保上传和下载目录存在
os.makedirs(settings.UPLOAD_DIR, exist_ok=True)
os.makedirs(settings.DOWNLOAD_DIR, exist_ok=True)

# 挂载静态文件服务
app.mount("/api/v1/downloads", StaticFiles(directory=settings.DOWNLOAD_DIR), name="downloads")

# 注册路由
app.include_router(doi.router, prefix="/api/v1/doi", tags=["doi"])
app.include_router(websocket.router, prefix="/api/v1/ws", tags=["websocket"])
app.include_router(database.router, prefix="/api/v1/database", tags=["database"])

# 依赖项：获取ARQ Redis连接
async def get_arq_redis() -> ArqRedis:
    return app.state.arq_redis
 

@app.get("/")
async def root():
    return {"message": "sci-hub Downloader API Service"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=settings.BACKEND_PORT)
    
#python -m app.main